package cloud.pangui.core.mongo.element;


import com.mongodb.MongoException;
import org.bson.Document;

/**
 * 属性，没有函数，就是一个简单的cloumn
 *
 * @Auther hepangui
 * @Date 2020/10/06 0001
*/
public class Field extends Ele {
	private Field() {
	}

	/**
	 * 对于简单的，无需任何函数的直接返回的key；
	 */
	private String key;

	/**
	 * 获取key值
	 *
	 * @return
	 */
	public String getKey() {
		return key;
	}

	/**
	 * 构建一个普通的field
	 *
	 * @param key
	 * @return
	 */
	public static Field of(String key) {
		if (key.indexOf("$") > -1 || key.indexOf("(") > -1 || key.indexOf(")") > -1) {
			throw new MongoException("field元素错误：" + key);
		}
		Field field = new Field();
		field.key = key;
		return field;
	}

	/**
	 * 将一组key转换为一组Field
	 *
	 * @param keys
	 * @return
	 */
	public static Field[] of(String[] keys) {
		Field[] fields = new Field[keys.length];
		for (int i = 0; i < keys.length; i++) {
			fields[i] = of(keys[i]);
		}
		return fields;
	}

	@Override
	public Object toExpression() {
		return "$" + key;
	}

	/**
	 * 单一属性的最外层构建逻辑
	 *
	 * @return
	 */
	@Override
	public Document build() {
		if (alias != null && !"".equals(alias)) {
			return new Document(alias, "$" + key);
		} else {
			return new Document(key, "$" + key);
		}
	}

	@Override
	public String getAlias() {
		if (alias != null && !"".equals(alias)) {
			return alias;
		} else {
			return key;
		}
	}
}
